package com.szsanshan.station.datacollector.util;

import cn.hutool.core.text.StrJoiner;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.TreeMap;

@Component
public class PetrolSignUtils {

    private static Logger LOGGER = LoggerFactory.getLogger(PetrolSignUtils.class);

    /**
     * 计算签名
     *
     * @param param
     * @return
     */
    public static String sign(TreeMap<String, String> param) {
        String appKey = param.remove("appKey");
        StrJoiner joiner = new StrJoiner("&");
        for (Map.Entry<String, String> each : param.entrySet()) {
            joiner.append(each.getKey() + "=" + each.getValue());
        }
        // 最后加上appKey
        joiner.append("appKey=" + appKey);
        LOGGER.debug("签名原文 : [{}]", joiner.toString());
        return DigestUtil.md5Hex(joiner.toString());
    }

    /**
     * 验证签名
     *
     * @param param
     * @return
     */
    public static boolean verify(TreeMap<String, String> param) {
        String originalSign = param.remove("sign");
        String sign = sign(param);
        LOGGER.debug("原密文 : [{}], MD5签名结果 : [{}]", originalSign, sign);
        boolean verify = sign.equals(originalSign);
        LOGGER.debug("签名验证结果: [{}]", verify ? "通过" : "不通过");
        return verify;
    }

    /**
     * 检验时间戳
     *
     * @param param
     * @return
     */
    public static boolean checkTimeStamp(TreeMap<String, String> param) {
        String timeStamp = param.get("timeStamp");
        if (StrUtil.isNotEmpty(timeStamp)) {
            long gap = System.currentTimeMillis() / 1000 - Long.parseLong(timeStamp);
            return Math.abs(gap) <= 300;
        }
        return false;
    }
}
